package com.example.dahua.proxy.dynamicProxy;

import com.example.dahua.proxy.staticProxy.BuyHouse;
import com.example.dahua.proxy.staticProxy.BuyHouseImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: dangwen
 * @createDate: 2021/7/3
 */
public class CglibProxy implements MethodInterceptor {
    private Object target;
    public Object getInstance(final Object target){
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
    @Override
    public Object intercept(Object object, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        preByHouse();
        Object invoke = methodProxy.invokeSuper(object, objects);
        afterByHouse();
        return invoke;
    }
    public void preByHouse(){
        System.out.println("请准备好钱!");
    }
    public void afterByHouse(){
        System.out.println("请带走房产证！");
    }
    public static void main(String[] args) {
        BuyHouse buyHouse = new BuyHouseImpl();
        CglibProxy cglibProxy = new CglibProxy();
        BuyHouseImpl buyHouse1 = (BuyHouseImpl) cglibProxy.getInstance(buyHouse);
        buyHouse1.byHouse();
    }

}
